using System;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
using DotNet.Utilities;

namespace WPFTemplateLib.WpfConverters
{
	/// <summary>
	/// [转换器] 枚举转参数中对应顺序的字符串（参数为以英文逗号分隔的字符串形式）
	/// </summary>
	/// <example>
	///	<![CDATA[
	///	{Binding Mode, Converter={StaticResource EnumToStrInParaConverter}, ConverterParameter='Edit, View, Copy To'}
	/// ]]>
	/// </example>
	public class EnumToStrInParaConverter : IValueConverter
	{
		/// <inheritdoc />
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			Enum myEnum = value as Enum;
			if(myEnum == null)
			{
				Console.WriteLine($"值[{value + ""}]不是枚举类型");
				return string.Empty;
			}

			try
			{
				string paraStr = parameter + "";
				var candidateList = paraStr.Split(',').Select(x => x.Trim()).ToList();
				int listLengh = candidateList.Count;
				int index = EnumExtension.GetEnumItemIndex(myEnum);
				if(index >= listLengh)
				{
					Console.WriteLine($"枚举[{myEnum}]索引[{index}]超出参数[{paraStr}]解析出的列表长度[{listLengh}]，将返回枚举字符串。");
					return myEnum.ToString();
				}
				else if(index < 0)
				{
					//应该不会发生;
					Console.WriteLine($"枚举[{myEnum}]索引[{index}]异常");
					return string.Empty;
				}
				else
				{
					return candidateList[index];
				}
			}
			catch(Exception ex)
			{
				Console.WriteLine($"发生异常：{ex}");
				return string.Empty;
			}
		}

		/// <inheritdoc />
		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}
}
